<?php
namespace Home\Controller;
use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Hook\BaseHook;
use Think\Cache\Driver\Redis;
use Think\Controller;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Log;
/*
 * 芝麻信用分
 *
 */
class Zmcontroller extends Controller{

    public function __construct()
    {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    //首先通过格式得到芝麻分反馈数据保存到.json文件
    public function getSaveJson(){

        $_date  = I('get.date');
        if (empty($_date)) {
            $_date = date('Y-m-d',time());
        }
        set_time_limit(0);
        try {
            $result =  M()->query("SELECT
			    #当前天
				DATE_FORMAT(
				FROM_UNIXTIME(ConsumeHistory.add_time),
				'%Y-%m-%d'
				) as date,

				# 身份证
				Customer.id_num,
				# 姓名
				Customer.real_name,
				# 订单号
				ConsumeHistory.id AS consume_id,
				# 场景类型
				ConsumeHistory.type,
				# 场景状态
				ConsumeHistory.`status`,
				# 金额
				ConsumeHistory.consume_amount AS  amount,
				# 应还日
				ConsumeHistory.repayment_time,
				#添加时间
				ConsumeHistory.add_time,
				# 违约累计金额
				CASE
			WHEN ConsumeHistory. STATUS = 3 THEN
				0
			WHEN (
				ConsumeHistory. STATUS = 1
				AND DATEDIFF(
					NOW(),
					FROM_UNIXTIME(
						ConsumeHistory.repayment_time
					)
				) > 0
			) THEN
				ConsumeHistory.consume_amount * 0.02 * DATEDIFF(
					NOW(),
					FROM_UNIXTIME(
						ConsumeHistory.repayment_time
					)
				) / 100 + ConsumeHistory.consume_amount / 100 + 50
			ELSE
				0
			END overdue_amount,
			 # 违约开始日期
			CASE
			WHEN ConsumeHistory. STATUS = 3 THEN
				0
			WHEN (
				ConsumeHistory. STATUS = 1
				AND DATEDIFF(
					NOW(),
					FROM_UNIXTIME(
						ConsumeHistory.repayment_time
					)
				) > 0
			) THEN
				DATE_FORMAT(
					FROM_UNIXTIME(
						ConsumeHistory.repayment_time + 86400
					),
					'%Y-%m-%d'
				)
			ELSE
				0
			END overdue_time
			FROM
				consume_history ConsumeHistory
			LEFT JOIN customer Customer ON Customer.id = ConsumeHistory.customer_id
			WHERE
				(
					ConsumeHistory.type IN (4,5)
					AND ConsumeHistory. STATUS IN (1, 3, 6, 7,  11, 12)
				)
			AND Customer.real_name IS NOT NULL # 日期
			AND DATE_FORMAT(
				FROM_UNIXTIME(ConsumeHistory.add_time),
				'%Y-%m-%d'
			) = '{$_date}'");

            if (!empty($result)) {
                $ret = array();
                $arr = array();
                $repayment_time='';
                foreach ($result as $k=>$v){
                    if($v['overdue_time'] == 0) {
                        if ($v['type'] == 4 && ($v['status'] == 6 || $v['status'] == 7 || $v['status'] == 11)) {
                            $status = 4;//审核拒绝
                            $repayment_time = date('Y-m-d',$v['add_time']);
                        } elseif ($v['type'] == 4 && $v['status'] == 12) {
                            $status = 5;//审核通过
                            $repayment_time = date('Y-m-d',$v['add_time']);

                        } elseif ($v['type'] == 5 && $v['status'] == 1) {
                            $status = 6;//服务使用
                            $repayment_time = date('Y-m-d',$v['add_time']);

                        } elseif ($v['type'] == 5 && $v['status'] == 3) {
                            $status = 2;//结清
                        }
                    }else{
                        $status = 1;//违约
                    }
                    if($repayment_time==''){
                        $repayment_time = date('Y-m-d',$v['repayment_time']);
                    }
                    $amount = $v['amount']/100;
                    if($v['overdue_time'] == 0){
                        $overdue_time = "";
                    }else{
                        $overdue_time = $v['overdue_time'];

                    }

                    $ret[] =  array(
                        'biz_date'=>''.$v['date'].'',
                        'linked_merchant_id'=>'2088621911021287',
                        'user_credentials_type'=>0,
                        'user_credentials_no'=>''.$v['id_num'].'',
                        'user_name'=>''.$v['real_name'].'',
                        'order_no'=>''.$v['consume_id'].'',
                        'scene_type'=>''.$v['type'].'',
                        'scene_desc'=>'',
                        'scene_status'=>''.$status.'',
                        'create_amt'=>''.$amount.'',
                        'installment_due_date'=>''.$repayment_time.'',
                        'overdue_amt'=>''.$v['overdue_amount'].'',
                        'gmt_ovd_date'=>''.$overdue_time.'',
                        'rectify_flag'=>'0',
                        'memo'=>''
                    );

                }
                $nums = count($ret);
                Log::bqs_zm_write("芝麻返回数据条数【".$nums."】");

                $arr['records'] = $ret;
                $jsonText = base64_encode(json_encode($arr));
                Log::bqs_zm_write("芝麻返回数据--start".$jsonText);
                $res = $this->zmBack($jsonText,$nums);
                Log::bqs_zm_write("芝麻返回数据--".json_encode($res));

                Log::bqs_zm_write("芝麻返回数据--end");

                $this->ajaxReturn($res);

            }else {
                $this->ajaxReturn(['code'=>'-1','msg'=>'数据null']);
            }
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }

    }



    /*
     * 白骑士芝麻数据反馈推送
     * @param text base64后的json格式数据
     * $param num 推送条数
     * */
    //https://api.baiqishi.com/credit/zhima/search

    public function zmBack($text,$num){
        try {
            if($text){

                $xml_data = array(
                    "linkedMerchantId"=> "2088621466717929",
                    "productId"=> "102003",
                    "extParam"=>array(
                        "fileCharset"=>"UTF-8",

                        "records" =>$num,
                        "primaryKeyColumns" =>"order_no,user_credentials_no",
                        "bizExtparams" =>"",
                        "file" =>$text,

                        "columns" =>"biz_date,linked_merchant_id,user_credentials_type,user_credentials_no,user_name,order_no,scene_type,scene_desc,scene_status,create_amt,installment_due_date,overdue_amt,gmt_ovd_date,rectify_flag,memo",
                    ),
                    "partnerId"=> "huoyanzichan",
                    "verifyKey" => "b21319571e6147c5a98ffc86cc144a11",
                );


                $ret = D('Zm')->data_back($xml_data);
                return $ret;
            }else{
                $ret = ['code' => 0, 'msg' => "芝麻返回数据--没有数据"];
                return $ret;
            }

        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
            return $ret;
        }



    }


    /*
     * 获得身份证和姓名接口
     * https://api.baiqishi.com/credit/zhima/search
     */

    // public function getUserData222(){
    //	var_dump(5555555555);die;
    //}
    public function getUserData(){
        try {//var_dump(999);
            Log::borrow_write("getUserData请求数据".I('post.').$_POST['idNum']);
            $Idnum = $_POST['idNum'];
            $Name = $_POST['name'];
            $information = D('Customer')->where(array("id_num"=>$Idnum))->find();
            Log::write("查看用户是否存在".json_encode($information));
            Log::borrow_write("getUserData校验用户存在".json_encode($information));
            //查看是否授权
            if($information){
                $xml_data = array(
                    "linkedMerchantId"=> "2088621466717929",
                    "productId"=> "102002",
                    "identityType"=> "2",
                    "partnerId"=> "huoyanzichan",
                    "extParam"=>array(
                        "callbackUrl"=>"http://api.huoyanzichan.com/zhima/index2.html",
                        "certNo"=>$Idnum,
                        "channel"=>"app",
                        "identityType"=>"2",
                        "name"=>$Name
                    ),
                    "verifyKey" => "b21319571e6147c5a98ffc86cc144a11",
                );
                Log::borrow_write("getUserData芝麻检查D(Zm )".json_encode($xml_data));
                $res = D('Zm')->checkauth($xml_data);
                Log::borrow_write("getUserData芝麻检查".$res);
                $json=json_decode($res,true);

                if(strcasecmp($json['resultData']['authorized'],"true")== 0){
                    $openId = $json['resultData']['openId'];
                    if($openId){
                        $xml_data2 = array(
                            "linkedMerchantId"=> "2088621466717929",
                            "productId"=> "102004",
                            "extParam"=>array(
                                "openId"=>$openId,
                            ),
                            "partnerId"=> "huoyanzichan",
                            "verifyKey" => "b21319571e6147c5a98ffc86cc144a11",
                        );

                        $zhimares = D('Zm')->getzhimascore($xml_data2);
                        $json2=json_decode($zhimares,true);
                        Log::borrow_write("getUserData芝麻分数获取".$zhimares);
                        $zmScore = $json2['resultData']['zmScore'];

                        if($zmScore){
                            $time = time();
                            $sqldata = array('sesame_score'=>$zmScore);
                            M('Customer')->where(['id_num'=>$Idnum])->setField($sqldata);
                            $data = [
                                'id_num'=>$Idnum,
                                'sesame_score'=>$zmScore,
                                'add_time'=>$time,
                                'version'=>$time
                            ];
                            M('CustomerSesame')->add($data);
                            M('Customer')->where(['id_num'=>$Idnum])->setField($sqldata);
                            /*****************************重新认证之后要清除逾期状态****************************************/
                            //       $china_mobile = M('CustomerAuth')->field('china_mobile')->where(['customer_id'=>$Cid['id']])->find();
                            // $cust = M('Customer')->where(['id'=>$Cid['id']])->find();
                            // $cust['china_mobile'] = $china_mobile['china_mobile'];
                            // if($cust['accreditation_status'] ==1 && !empty($cust['china_mobile']) ){
                            //     $data1 = [
                            //         'accreditation_status'=>0
                            //     ];
                            //     Log::rong_write("*******customerFewMsg|". $Cid['id'] ."accreditation_status|字段清零*******：");
                            //     $saveRes = M('Customer')->where(['id'=>$Cid['id']])->save($data1);
                            //     Log::rong_write("*******customerFewMsg|accreditation_status|字段清零结果|". $saveRes ."*******：");
                            // }
                            /*****************************重新认证之后要清除逾期状态****************************************/
                            Log::borrow_write("getUserData获取芝麻分成功".$zmScore);
                            $this->ajaxReturn(['code' => 0, 'msg' => "获取芝麻分成功", 'zmscort' => $zmScore]);
                        }else{
                            Log::borrow_write("getUserData获取芝麻分不存在".$zmScore);
                        }
                    }
                }else{
                    //未授权
                    $xml_data3 = array(
                        "linkedMerchantId"=> "2088621466717929",
                        "productId"=> "102001",
                        "extParam"=>array(
                            "callbackUrl"=>"http://api.huoyanzichan.com/zhima/index2.html",
                            "certNo"=>$Idnum,
                            "channel"=>"app",
                            "identityType"=>"2",
                            "name"=>$Name
                        ),
                        "partnerId"=> "huoyanzichan",
                        "verifyKey" => "b21319571e6147c5a98ffc86cc144a11",
                    );
                    $zhimaopenid = D('Zm')->getzhimaopenid($xml_data3);
                    $json3=json_decode($zhimaopenid,true);
                    $callbackurl = $json3['resultData']['authInfoUrl'];

                    if($callbackurl){
                        $this->ajaxReturn(['code' => 0, 'msg' => "获取跳转链接成功", 'callbackurl' => $callbackurl]);
                    }
                }
            }
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
//         $ret = Response::format($ret);
//         $this->ajaxReturn($ret);
    }
}


